package com.gjs.management.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjs.common.exception.BizException;
import com.gjs.management.mapper.AgreementMapper;
import com.gjs.management.pojo.dto.agreement.AgreementQueryDTO;
import com.gjs.management.pojo.dto.config.ConfigQueryDTO;
import com.gjs.management.pojo.entity.Agreement;
import com.gjs.management.pojo.entity.Config;
import com.gjs.management.service.IAgreementService;
import com.gjs.management.service.IConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class AgreementServiceImpl extends ServiceImpl<AgreementMapper, Agreement> implements IAgreementService {

    private final IConfigService configService;

    @Override
    public Agreement getAgreementByConfigKey(String agreementConfigKey){
        ConfigQueryDTO configQueryDTO = new ConfigQueryDTO();
        configQueryDTO.setConfigKey(agreementConfigKey);
        Config config = configService.getOne(configService.buildWrapper(configQueryDTO));
        if(config == null){
            throw new BizException(StrUtil.format("协议配置[{}]不存在",agreementConfigKey));
        }

        Agreement agreement = this.getById(config.getConfigValue());
        if(agreement == null || StrUtil.isEmpty(agreement.getContent())){
            throw new BizException("找不到对应协议");
        }

        return agreement;
    }

    @Override
    public Wrapper<Agreement> buildWrapper(AgreementQueryDTO queryDTO){
        LambdaQueryWrapper<Agreement> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(queryDTO.getId() != null && queryDTO.getId() > 0,Agreement::getId,queryDTO.getId());
        wrapper.eq(!StrUtil.isEmpty(queryDTO.getAgreementName()),Agreement::getAgreementName,queryDTO.getAgreementName());

        return wrapper;
    }
}
